<?php

namespace Admin\Logic;

use Common\Utils\Constants;
use Common\Utils\TemplateUtils;
use Think\Exception;
use Think\Log;

/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/15
 * Time: 15:32
 */
class MatchLogic
{
    /**
     * 比赛判定输赢
     * @param $winner_id int 获胜者
     * @param $log_id int 记录id
     * @return int 0该比赛无法判定 1判定成功 2判定失败 3获胜者不在该比赛中
     */
    public function judge($winner_id,$log_id){
        $log = D('MatchLog')->where(array('id'=>$log_id))->find();
        if($log['user_id'] != $winner_id && $log['opponent_id'] !=$winner_id){
            return 3;
        }
        if($log['status'] != Constants::MATCH_IN){
            return 0;
        }
        $model = M();
        $model->startTrans();
        try{
            //修改胜利者积分
            $room = $model->table('t_room')->where(array('id'=>$log['room_id']))->find();

            $system_integral = $this->countPoundage($room['integral'],$model);//系统提成
            $integral = $room['integral'] * 2  - $system_integral ;

            //修改比赛状态
            $model->table('t_match_log')->where(array('id'=>$log_id))->setField('winner',$winner_id);
            $model->table('t_match_log')->where(array('id'=>$log_id))->setField('status',Constants::MATCH_END);
            $model->table('t_match_log')->where(array('id'=>$log_id))->setField('reward_money',$integral);//设置奖励多少

            //修改房间状态
            $model->table('t_room')->where(array('id'=>$room['id']))->setField('status',Constants::ROOM_STATUS_END);

            $winner = $model->table('t_user')->where(array('id'=>$winner_id))->find();
            $failUser = $this->getFailUser($winner['id'],$log);

            if($room['money_type'] == Constants::MONEY_TYPE_GOLD) {
                $model->table('t_user')->where(array('id' => $winner_id))->setInc('gold', $integral);
            }else{
                $model->table('t_user')->where(array('id' => $winner_id))->setInc('integral', $integral);
            }
            //修改用户比赛记录
            $model->table('t_user')->where(array('id'=>$failUser['id']))->setInc('total_number',1);
            $model->table('t_user')->where(array('id'=>$winner['id']))->setInc('win_number',1);
            $model->table('t_user')->where(array('id'=>$winner['id']))->setInc('total_number',1);

            $model_type = $room['model'];
            if($model_type >= Constants::MODEL_TYPE_5V5){
                $model_type = Constants::MODEL_TYPE_5V5;
            }
            $model->table('t_ranking')->where(array('user_id'=>$failUser['id'],'type'=>$model_type))->setInc('total_number',1);
            $model->table('t_ranking')->where(array('user_id'=>$winner['id'],'type'=>$model_type))->setInc('win_number',1);
            $model->table('t_ranking')->where(array('user_id'=>$winner['id'],'type'=>$model_type))->setInc('total_number',1);

            $remark = '和'.$failUser['nickname'].'对战获胜(用户ID:'.$failUser['id'].')';
            $moneyLogic = new MoneyLogLogic();
            $moneyLogic->saveMoneyLog($integral,$winner['integral'],
                Constants::MONEY_SOURCE_WIN,//获胜
                Constants::PUT_TYPE_IN,$remark,$winner['id'],$room['money_type'],$model);
            if($room['money_type'] == Constants::MONEY_TYPE_INTEGRAL) {
                $this->rebateLog($winner['last_one'], $system_integral, $winner, $model);//系统提成后代理提成
                $this->rebateLog($failUser['last_one'], $system_integral, $failUser, $model);//系统提成后代理提成
            }
            $model->commit();
            //发送模版消息
            $this->sendVerifyMessage($failUser['id'],$room['id'],0);//失败者发送失败消息
            $this->sendVerifyMessage($winner_id,$room['id'],1);//胜利者
            return 1;
        }catch (Exception $e){
            Log::write($e->getMessage());
            $model->rollback();
            return 2;
        }
    }

    /**计算系统提成
     * @param $integral
     * @param $model
     * @return int
     */
    private function countPoundage($integral,$model){
        $config = $model->table('t_config')->where(array('name'=>Constants::CONFIG_WIN_SYSTEM_POUNDAGE))->find();
        if(!is_numeric($config['value'])){
            return 0;
        }
        $money = round($config['value'] * $integral);
        if($money <= 0){
            return 0;
        }else{
            return $money;
        }
    }

    /**
     * 代理返点
     * @param $user_id  int 代理
     * @param $integral int 系统抽成部分
     * @param $winner array 胜利者
     * @param $model
     */
    private function rebateLog($user_id,$integral,$winner,$model){
        if(empty($user_id)){
            return;
        }
        $user = D('User')->where(array('id'=>$user_id))->find();
        if($user && $user['rebate_percentage'] > 0){
            $money = round($user['rebate_percentage'] * $integral) / 10;
            if($money <= 0){
                return;
            }
//            $model->table('t_user')->where(array('id'=>$user_id))->setInc('integral',$money);
            $model->table('t_user')->where(array('id'=>$user_id))->setInc('income',$money);//代理收入
            $user = $model->table('t_user')->where(array('id'=>$user_id))->find();
            $moneyLogic = new MoneyLogLogic();
            $remark = $winner['nickname'].'对战获得提成(用户ID:'.$winner['id'].')';
            $moneyLogic->saveMoneyLogBySourceId($money,$user['income'],
                Constants::MONEY_SOURCE_REBATE,//代理抽成
                Constants::PUT_TYPE_IN,$remark,$user_id,Constants::MONEY_TYPE_INCOME,$winner['id'],$model);
        }
    }

    //发送审核消息
    private function sendVerifyMessage($user_id,$room_id,$type){
        $utils = new TemplateUtils();
        $user = D('User')->where(array('id'=>$user_id))->field('openid,nickname')->find();
        $utils->sendVerifyMessage($user['openid'],$user['nickname'],$room_id,$type);
    }

    private function getFailUser($winner,$log){
        if($log['opponent_id'] == $winner){
            $user_id = $log['user_id'];
        }else{
            $user_id = $log['opponent_id'];
        }
        return D('User')->where(array('id'=>$user_id))->find();
    }

    /**
     * 清除场次榜信息
     * @param $level int 榜前名次
     * @param $type int 类型 0 1v1 1 3v3 2 5v5
     * @return array status 0失败 1成功 2请设置场次榜上榜所需场次
     */
    public function clearRankInfo($level,$type){
        $model = M();
        $model->startTrans();
        try{
            $battle_times  = D('Config')->where(array('name'=>Constants::CONFIG_BATTLE_TIMES))->find();
            $battle_times = $battle_times['value'];
            if(empty($battle_times) || !is_numeric($battle_times) || $battle_times <=0){
                return array('status'=>2);
            }
            $userList = D('Ranking')
                ->field('t_ranking.user_id,t_ranking.total_number,t_ranking.win_number')
                ->where(array('t_ranking.total_number'=>array('EGT',$battle_times),'t_ranking.type'=>$type))
                ->order('t_ranking.total_number desc,t_ranking.user_id asc')->limit(0,$level)->select();
            foreach ($userList as $key=>$value){
                //修改用户场次榜信息
                $map['type'] = $type;
                $map['user_id'] = $value['user_id'];
                $model->table('t_ranking')->where($map)
                    ->setField(array('win_number'=>0,'total_number'=>0));
                //删除比赛记录
                $this->clearMatchLog($value['user_id'],$type,$model);
            }
            $model->commit();
            return array('status'=>1);
//            return array('status'=>0,'error'=>$userList);
        }catch (Exception $e){
            return array('status'=>0,'error'=>$e->getMessage());
        }
    }

    private function clearMatchLog($user_id,$type,$model){
        $where['_string'] = ' t_match_log.user_id = '.$user_id.' OR'.' t_match_log.opponent_id = '.$user_id;
        $map['_complex'] = $where;
        if($type == Constants::MODEL_TYPE_5V5){
            $map['model'] = array('EGT',Constants::MODEL_TYPE_5V5);
        }else{
            $map['model'] = $type;
        }

        $list = $model->table('t_match_log')
            ->where($map)
            ->field('id,user_id,opponent_id')
            ->select();
        foreach ($list as $key=>$value){
            if($value['user_id'] == $user_id){
                $field = 'is_user_delete';
            }else{
                $field = 'is_opponent_delete';
            }
            $model->table('t_match_log')->where(array('id'=>$value['id']))->setField($field,$user_id);
        }
    }
}